package com.zues.thread.design_mode.produce_consumer;

import lombok.extern.slf4j.Slf4j;

import java.util.LinkedList;

/**
 * 消息队列类 Java线程之间通信
 */
@Slf4j(topic = "c.MessageQueue")
public class MessageQueue {

    //消息的队列集合
    private final LinkedList<Message> list = new LinkedList<Message>();
    //队列容量
    private int capacity;

    public MessageQueue(int capacity) {
        this.capacity = capacity;
    }


    //获取消息的方法
    public Message take() {
        synchronized (list){
            while(list.isEmpty()){
                try {
                    log.debug("队列为空，消费者线程等待");
                    list.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            //从队列头部获取消息并返回
            Message message = list.removeFirst();
            log.debug("已消费消息：{}",message);
            list.notifyAll();
            return message;
        }
    }

    //存储消息的方法
    public void put(Message message) {
        synchronized (list){
            while(list.size() == capacity){
                try {
                    log.debug("队列已满，生产者线程等待");
                    list.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            //消息加入队列
            list.addLast(message);
            log.debug("已生产消息：{}",message);
            list.notifyAll();
        }
    }
}
